|
A smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic memory management or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the memory they point to. They may also be used to manage other resources, such as network connections and file handles. Smart pointers originated in the C++ programming language. Misuse of pointers can be a major source of bugs. Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic. More generally, they make object destruction automatic: the object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of the object is destroyed, for example because the owner is a local variable, and execution leaves the variable's scope. Smart pointers also eliminate dangling pointers by postponing destruction until the object is no longer in use. Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of the object to a single pointer. If a language supports automatic garbage collection (for instance, Java or C#), then smart pointers are not needed for the reclamation and safety aspects of memory management, but are nevertheless useful for other purposes, such as cache data structure residence management and resource management of objects such as file handles or network sockets. == Features == In C++, a smart pointer is implemented as a template class that mimics, by means of operator overloading, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features. Smart pointers can facilitate intentional programming by expressing in the type itself how the memory of the referent of the pointer will be managed. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory of the referent when the caller is finished with the information. Traditionally, naming conventions have been used to resolve the ambiguity, which is an error-prone, labor-intensive approach. C++11 introduced a way to ensure correct memory management in this case by declaring the function to return a unique_ptr ,The declaration of the function return type as a unique_ptr makes explicit the fact that the caller takes ownership of the result, and the C++ runtime ensures that the memory for *some_type will be reclaimed automatically. Prior to C++11, unique_ptr can be replaced with auto_ptr. 抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「smart pointer」の詳細全文を読む スポンサード リンク
|